#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

#define RESOURCE 5

sem_t sem_producer,sem_consumer;

pthread_mutex_t mutex;

typedef struct Node{
    int number;
    struct Node *next;
}Node;

Node* head=NULL;

/* 生产者 */
void* producer(void* arg){
    while(1){
        sem_wait(&sem_producer);
        Node* newNode=calloc(1,sizeof(Node));
        newNode->number=rand()%1000;
        newNode->next=head;
        head=newNode;
        printf("生产者 id: %ld , number: %d \n",pthread_self(),newNode->number);
        sem_post(&sem_consumer);
        sleep(rand()%3);
    }
    pthread_exit(NULL);
}
/* 消费者 */
void* consumer(void* arg){
    while(1){
        sem_wait(&sem_consumer);
        Node* node=head;
        printf("消费者 id: %ld , number: %d \n",pthread_self(),node->number);
        head=head->next;
        free(node);
        sem_post(&sem_producer);
        sleep(rand()%2);
    }
    pthread_exit(NULL);
}

int main()
{
    pthread_t t1[5],t2[5];
    int len=sizeof(t1)/sizeof(t1[1]);

    sem_init(&sem_producer,0,RESOURCE);
    sem_init(&sem_consumer,0,0);
    
    pthread_mutex_init(&mutex,NULL);
    
    for(int i=0;i<len;i++){
        pthread_create(t1+1,NULL,producer,NULL); 
        pthread_create(t2+1,NULL,consumer,NULL); 
    }
    
    for(int i=0;i<len;i++){
        pthread_join(t1[i],NULL);
        pthread_join(t2[i],NULL);
    }

    sem_destroy(&sem_producer);
    sem_destroy(&sem_consumer);

    pthread_mutex_destroy(&mutex);
    return 0;
}

